# coding: utf-8

"""
    @Author :   zsj
    @File   :   base_router.py
    @Time   :   2024-08-12
    @Desc   :   基础路由类，封装通用的API路由
"""

from fastapi import APIRouter, Depends
from typing import Type, Optional, Generic, TypeVar
from sqlmodel import SQLModel
from src.common.base_service import BaseService
from src.core.logconfig import log

logger = log.logger

T = TypeVar('T', bound=SQLModel)
CreateSchema = TypeVar('CreateSchema', bound=SQLModel)
UpdateSchema = TypeVar('UpdateSchema', bound=SQLModel)
OutSchema = TypeVar('OutSchema', bound=SQLModel)


class BaseRouter(Generic[T, CreateSchema, UpdateSchema, OutSchema]):
    """基础路由类，提供通用的API路由"""
    
    def __init__(self, 
                 entity: Type[T] = None, 
                 create_schema: Type[CreateSchema] = None,
                 update_schema: Type[UpdateSchema] = None,
                 out_schema: Optional[Type[OutSchema]] = None,
                 prefix: str = "", 
                 tags: Optional[list] = None):
        """
        初始化路由类
        
        Args:
            entity: 数据库实体类
            create_schema: 创建数据模型类
            update_schema: 更新数据模型类
            out_schema: 输出数据模型类（可选）
            prefix: 路由前缀
            tags: 路由标签
        """
        self.router = APIRouter(prefix=prefix, tags=tags or [entity.__name__])
        self.service = BaseService(entity)
        self.entity = entity
        self.create_schema = create_schema
        self.update_schema = update_schema
        self.out_schema = out_schema or entity
        
        # 注册通用路由
        self._register_routes()
    
    def _register_routes(self):
        """注册通用路由"""
        
        @self.router.post("/list", description="获取数据列表")
        async def get_list():
            return await self.service.get_list()
        
        @self.router.post("/query", description="根据ID获取数据")
        async def get_by_id(id: int):
            return await self.service.get_by_id(id)
        
        @self.router.post("/create", response_model=self.out_schema, description="创建新数据")
        async def create(data: self.create_schema):
            return await self.service.create(data)
        
        @self.router.post("/update", description="更新数据")
        async def update(data: self.update_schema):
            return await self.service.update(data)
        
        @self.router.post("/delete", description="删除数据")
        async def delete(id: int):
            return await self.service.delete(id)
    
    def get_router(self):
        """获取APIRouter实例"""
        logger.info("router: ", self.router)
        return self.router